"use client"

import type React from "react"
import { useState, useMemo } from "react"
import { Card, Typography, Space, Button, Input, Empty, Collapse, Tag, Row, Col, Pagination } from "antd"
import { DownOutlined, RightOutlined, SearchOutlined, PlusOutlined, CloseOutlined } from "@ant-design/icons"
import type { Host, HostType } from "../types"
import { HOST_TYPE_NAMES } from "../types"
import HostCard from "./HostCard"

const { Text } = Typography
const { Panel } = Collapse

interface HostsGroupProps {
  category: string
  hosts: Host[]
  onAddHost: (category: string) => void
  onEditHost: (host: Host) => void
  onDeleteHost: (id: string) => void
  onCopyHost?: (host: Host) => void
}

const HOSTS_PER_PAGE = 9

export const HostsGroup: React.FC<HostsGroupProps> = ({
  category,
  hosts,
  onAddHost,
  onEditHost,
  onDeleteHost,
  onCopyHost,
}) => {
  const [isExpanded, setIsExpanded] = useState(true)
  const [searchText, setSearchText] = useState("")
  const [showSearch, setShowSearch] = useState(false)
  const [currentPage, setCurrentPage] = useState(1)

  // 按类型分组
  const groupedHosts = useMemo(() => {
    const filtered = hosts.filter((host) => {
      if (!searchText) return true
      return (
        host.title.toLowerCase().includes(searchText.toLowerCase()) ||
        host.ip.includes(searchText) ||
        host.domain.toLowerCase().includes(searchText) ||
        (host.description && host.description.toLowerCase().includes(searchText.toLowerCase()))
      )
    })

    return filtered.reduce(
      (acc, host) => {
        if (!acc[host.type]) {
          acc[host.type] = []
        }
        acc[host.type].push(host)
        return acc
      },
      {} as Record<HostType, Host[]>,
    )
  }, [hosts, searchText])

  const typeOrder: HostType[] = ["frontend", "backend", "database", "cache", "other"]

  // 计算总条目数
  const totalItems = useMemo(() => {
    return Object.values(groupedHosts).reduce((sum, hosts) => sum + hosts.length, 0)
  }, [groupedHosts])

  // 分页逻辑
  const paginatedHosts = useMemo(() => {
    const allHosts = Object.values(groupedHosts).flat()
    const start = (currentPage - 1) * HOSTS_PER_PAGE
    const end = start + HOSTS_PER_PAGE
    return allHosts.slice(start, end)
  }, [groupedHosts, currentPage])

  const handlePageChange = (page: number) => {
    setCurrentPage(page)
  }

  return (
    <Card className="hosts-group" style={{ marginBottom: 16 }} bodyStyle={{ padding: 0 }}>
      <div
        style={{
          padding: "12px 24px",
          borderBottom: "1px solid #f0f0f0",
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          cursor: "pointer",
          backgroundColor: isExpanded ? "transparent" : "#fafafa",
        }}
        onClick={() => setIsExpanded(!isExpanded)}
      >
        <Space>
          {isExpanded ? <DownOutlined /> : <RightOutlined />}
          <Text strong>{category}</Text>
          <Tag>{totalItems}</Tag>
        </Space>

        <Space>
          <Button
            type="text"
            icon={showSearch ? <CloseOutlined /> : <SearchOutlined />}
            onClick={(e) => {
              e.stopPropagation()
              setShowSearch(!showSearch)
              if (!showSearch) {
                setSearchText("")
                setCurrentPage(1)
              }
            }}
          />
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={(e) => {
              e.stopPropagation()
              onAddHost(category)
            }}
          >
            添加
          </Button>
        </Space>
      </div>

      {isExpanded && (
        <div style={{ padding: 24 }}>
          {showSearch && (
            <div style={{ marginBottom: 16 }}>
              <Input
                placeholder="搜索主机..."
                prefix={<SearchOutlined />}
                value={searchText}
                onChange={(e) => {
                  setSearchText(e.target.value)
                  setCurrentPage(1)
                }}
                allowClear
              />
            </div>
          )}

          {totalItems === 0 ? (
            <Empty description="暂无数据" />
          ) : (
            <>
              <Collapse defaultActiveKey={typeOrder} ghost expandIconPosition="start">
                {typeOrder.map((type) => {
                  const typeHosts = groupedHosts[type] || []
                  if (typeHosts.length === 0) return null

                  return (
                    <Panel
                      key={type}
                      header={
                        <Space>
                          <Text>{HOST_TYPE_NAMES[type]}</Text>
                          <Tag>{typeHosts.length}</Tag>
                        </Space>
                      }
                    >
                      <Row gutter={[16, 16]}>
                        {paginatedHosts
                          .filter((host) => host.type === type)
                          .map((host) => (
                            <Col xs={24} sm={12} md={8} key={host.id}>
                              <HostCard host={host} onEdit={onEditHost} onDelete={onDeleteHost} onCopy={onCopyHost} />
                            </Col>
                          ))}
                      </Row>
                    </Panel>
                  )
                })}
              </Collapse>

              {totalItems > HOSTS_PER_PAGE && (
                <div style={{ textAlign: "right", marginTop: 16 }}>
                  <Pagination
                    current={currentPage}
                    total={totalItems}
                    pageSize={HOSTS_PER_PAGE}
                    onChange={handlePageChange}
                    showSizeChanger={false}
                  />
                </div>
              )}
            </>
          )}
        </div>
      )}
    </Card>
  )
}

export default HostsGroup
